package com.hqyj.service.impl;

import com.hqyj.dao.UserInfoMapper;
import com.hqyj.pojo.RoleInfo;
import com.hqyj.pojo.UserInfo;
import com.hqyj.service.ExcelService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
@Service
public class ExcelServiceImpl implements ExcelService {
    @Autowired(required = false)
    UserInfoMapper userInfoMapper;
    @Override
    public void excel(HttpServletResponse response) {
        //定义要导出的数据
        List<UserInfo> list = userInfoMapper.select();
        //操作office文件对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建excel
        HSSFSheet sheet =  workbook.createSheet("用户信息表");
        // 创建一行作表头信息
        HSSFRow colName = sheet.createRow(0);
        //定义表头信息,都是自定义的
        String[] title = {"编号","登录名","手机","邮箱","角色","状态"};
        //在excel中写入表头
        for (int i =0;  i<title.length; i++){
            colName.createCell(i).setCellValue(title[i]);
        }
        //写入要导出的数据
        for (int i = 0; i<list.size(); i++){
            //创建写入的行，从第二行开始写入数据
            HSSFRow row = sheet.createRow(i+1);
            //写入编号列 第一列
            row.createCell(0).setCellValue(list.get(i).getuId());

            row.createCell(1).setCellValue(list.get(i).getUserName());
            row.createCell(2).setCellValue(list.get(i).getUserDetail().getPhone());
            row.createCell(3).setCellValue(list.get(i).getUserDetail().getEmail());
            String info ="";
            for (RoleInfo roleInfo:list.get(i).getRoleInfoList()){
                info +=roleInfo.getrName()+"";
            }
            row.createCell(4).setCellValue(info);
            row.createCell(5).setCellValue(list.get(i).getUserDetail().getState());
        }
        String fileName = "用户列表";
        try {
            //解决下载文件中文乱码问题
            fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        }catch (IOException e){
            e.printStackTrace();
        }

        //设置相应方式
        response.reset();
        //设置相应文件的名字
        response.setHeader("Content-disposition", "attachment; filename="+fileName+".xls");
        //设置下载文件的类型excel类型就是msexcel
        response.setContentType("application/msexcel");
        try {
            //写入你要下载文件
            workbook.write(response.getOutputStream());
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
